//
//  MTCheckoutController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/6.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory

class MTCheckoutController: BaseViewController {
    var model: MineWithdrawModel? {
        didSet {
            totalAmount.text = "最高可结算\(model?.enableMoney ?? 0)元"
            checkoutAmount.text = "可结算金额\(model?.actualWithDrawMoney ?? 0)元"
        }
    }
    
    lazy var totalAmount: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex:0x9b9b9b)
        label.font = PingFangSCMediumFont(12)
        label.textAlignment = .center
        return label
    }()
    
    lazy var inputLab: UILabel = {
        let label = UILabel()
        label.text = "输入结算金额"
        label.textColor = UIColor(hex:0x1d1a1a)
        label.font = PingFangSCSemiboldFont(14)
        label.textAlignment = .center
        return label
    }()
    
    lazy var leftView: UILabel = {
        let l = UILabel()
        l.text = "￥"
        l.frame = CGRect(x: 0, y: 0, width: 30, height: 56)
        l.textColor = UIColor(hex:0x1d1a1a)
        l.font = PingFangSCSemiboldFont(40)
        return l
    }()
    
    lazy var moneyTxt: UITextField = {
        let text = UITextField()
        text.textAlignment = .center
        text.textColor = UIColor(hex:0x1d1a1a)
        text.font = PingFangSCSemiboldFont(40)
        text.keyboardType = .decimalPad
        text.leftView = leftView
        text.leftViewMode = .always
        return text
    }()
    
    lazy var checkoutAmount: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex:0x1d1a1a)
        label.font = PingFangSCMediumFont(14)
        label.textAlignment = .center
        return label
    }()
    
    lazy var taskButton: UIButton = {
        let button = UIButton()
        button.setTitle("提高提现比例 >", for: .normal)
        button.setTitleColor(UIColor(hex:0x426bf2), for: .normal)
        button.titleLabel?.font = PingFangSCMediumFont(12)
        button.addTarget(self, action: #selector(checkoutViewController(didClickRuleButton:)), for: .touchUpInside)
        return button
    }()
    
    lazy var nextStepButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("下一步", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 25
        btn.backgroundColor = UIColor(hex:0xffc000)
        btn.clipsToBounds = true
        btn.addTarget(self, action: #selector(checkoutViewController(didClickNextButton:)), for: .touchUpInside)
        return btn
    }()
}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MTCheckoutController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeUI()
        view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissKeyBoard)))
    }
    
    @objc private func dismissKeyBoard() {
        self.moneyTxt.endEditing(true)
    }
    
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MTCheckoutController {
    
    private func initializeUI() {
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        navigationItem.title = "结算"
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 56, height: 20))
        button.setTitle("联系客服", for: .normal)
        button.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        button.titleLabel?.font = PingFangSCMediumFont(14)
        button.addTarget(self, action: #selector(checkoutViewController(didClickContactButton:)), for: .touchUpInside)
        let rightBarButton = UIBarButtonItem(customView: button)
        self.navigationItem.rightBarButtonItem = rightBarButton
        
        view.addSubview(totalAmount)
        view.addSubview(inputLab)
        view.addSubview(moneyTxt)
        view.addSubview(checkoutAmount)
        view.addSubview(taskButton)
        view.addSubview(nextStepButton)
        
        totalAmount.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(35+NavigationBarHeight+StatusBarHeight)
            make.centerX.equalTo(view)
            make.width.equalTo(200)
        }
        
        inputLab.snp.makeConstraints { (make) in
            make.top.equalTo(totalAmount.snp.bottom).offset(5)
            make.centerX.equalTo(view)
            make.width.equalTo(200)
        }
        
        moneyTxt.snp.makeConstraints { (make) in
            make.top.equalTo(inputLab.snp.bottom).offset(5)
            make.centerX.equalTo(view)
            make.width.equalTo(200)
        }

        checkoutAmount.snp.makeConstraints { (make) in
            make.top.equalTo(moneyTxt.snp.bottom).offset(35)
            make.centerX.equalTo(view)
            make.width.equalTo(200)
        }
        
        taskButton.snp.makeConstraints { (make) in
            make.top.equalTo(checkoutAmount.snp.bottom).offset(10)
            make.centerX.equalTo(view)
        }
        
        nextStepButton.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(50)
            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 20)
        }
    }
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTCheckoutController {
    
    private func checkoutViewController(didClickContactButton sender: UIButton) {
        if let un = UserCenter.default.customerUserName {
            JMSGConversation.createSingleConversation(withUsername: un) { [weak self] (conversation, error) in
                guard let weakSelf = self else { return }
                if error == nil, conversation != nil {
                    if let nav = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.viewControllers?[1] as? BaseNavController {
                        nav.selectCategory()
                        
                        DispatchQueue.main.after(0.25) {
                            let conv: JMSGConversation = conversation as! JMSGConversation
                            nav.pushViewController(JCChatViewController(conversation: conv), animated: true)
                        }
                        
                        DispatchQueue.main.after(1, execute: {
                            weakSelf.navigationController?.popToRootViewController(animated: false)
                        })
                    }
                }
            }
        }
    }
    
    private func checkoutViewController(didClickNextButton sender: UIButton) {
        if moneyTxt.text?.count == 0 {
            AlertManager.presentAlertView(message: "请输入结算金额")
            return
        }
        let xibView = MTWithdrawBindAccountAlertView.init(frame: CGRect(x:0, y:0, width:ScreenWidth, height:ScreenHeight))
        xibView.model = model
        xibView.completionHandler = {(type: Int) -> Void in
            self.bindAccountInfo(type: type)
        }
        self.view.addSubview(xibView)
    }
    
    private func checkoutViewController(didClickRuleButton sender: UIButton) {
        let vc: MTWithdrawTaskListController = MTWithdrawTaskListController()
        vc.rate = model?.withdrawRate ?? 0
        navigationController?.pushViewController(vc, animated: true)
    }
    
    private func bindAccountInfo(type: Int){
        if type == 1 {
            if model?.aliStatus ?? false {
                ///已绑定支付宝账号，直接结算
                let vc = MTWithdrawConfirmController()
                vc.money = moneyTxt.text ?? ""
                vc.requestParams = ["account": model?.aliAccount?.account ?? "",
                                    "typeId"     : 1,
                                    "userName"   : model?.aliAccount?.userName ?? "",
                                    "withdrawMoney": moneyTxt.text ?? "0"]
                navigationController?.pushViewController(vc, animated: true)
            } else {
                let vc = MTWithdrawBindCardController()
                vc.isBank = type == 2
                vc.money = self.moneyTxt.text ?? "0"
                self.navigationController?.pushViewController(vc, animated:    true)
            }
        } else {
            if model?.bankStatus ?? false {
                ///已绑定银行卡，直接结算
                let vc = MTWithdrawConfirmController()
                vc.money = moneyTxt.text ?? ""
                vc.requestParams = ["account": model?.bankAccount?.account ?? "",
                                    "typeId"     : 1,
                                    "userName"   : model?.bankAccount?.userName ?? "",
                                    "withdrawMoney": moneyTxt.text ?? "0"]
                navigationController?.pushViewController(vc, animated: true)
            } else {
                let vc = MTWithdrawBindCardController()
                vc.isBank = type == 2
                vc.money = self.moneyTxt.text ?? "0"
                self.navigationController?.pushViewController(vc, animated:    true)
            }
        }
    }
    
}

